<template>
  <div>
    <el-dialog
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      :title="title"
      align="left"
      :append-to-body="true"
      :visible.sync="innerDialogFormVisible"
      :before-close="handleClose"
    >
      <p slot="title">{{ title }}</p>
      <el-form
        ref="formData"
        :model="formData"
        class="base-pipeline-layout"
        label-width="130px"
        :rules="formRules"
        status-icon
      >
        <el-form-item label="报告编号类型">
          <el-select
            v-model="formData.reportNumberTypeEnum"
            placeholder="请选择"
            @change="reportNumberTypeChange"
          >
            <el-option
              v-for="item in reportNumTypeData"
              :key="item.value"
              :label="item.name"
              :value="Number(item.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报告编号" prop="reportNum">
          <el-input
            v-model="formData.reportNum"
            autocomplete="off"
            :disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="编写人" prop="permissionUserName">
          <el-input
            v-model="formData.permissionUserName"
            autocomplete="off"
            style="width: 215px"
          ></el-input>
          <div class="chioseUser" @click="chioseUser">+</div>
        </el-form-item>
        <el-form-item label="编写日期" prop="compileDate">
          <el-date-picker
            v-model="formData.compileDate"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item
          label="报告形式"
          prop="reportTypeCode"
          style="width: 100%"
        >
          <el-radio-group
            v-model="formData.reportTypeCode"
            style="width: 100%"
            @change="radioChange"
          >
            <el-radio
              v-for="(item, index) in reportTypeList"
              :key="index"
              :label="Number(item.value)"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="报告模板"
          :prop="reportTemplateProp"
          style="width: 100%"
        >
          <el-select
            :key="timer"
            v-model="formData.reportTemplateId"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in reportTemplateList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
              :disabled="reportTemplateState[index]"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否评价"
          prop="reportConclusionEnum"
          style="width: 100%"
        >
          <el-radio-group
            v-model="formData.reportConclusionEnum"
            style="width: 100%"
          >
            <el-radio
              v-for="(item, index) in reportConclusionTypeData"
              :key="index"
              :label="Number(item.value)"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="base-dialog-footer">
        <el-button type="primary" :disabled="downloadState" @click="download"
          >下 载</el-button
        >
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="handleClose">取 消</el-button>
        <!-- <el-button @click="preview">预览</el-button> -->
      </span>
      <AmbientGas
        ref="AmbientGas"
        v-model="isShowAmbientGasDialog"
        :report-data.sync="reportData"
      />
      <DieselOil
        ref="DieselOil"
        v-model="isShowDieselOilDialog"
        :report-data.sync="reportData"
        @closeGasoline="closeDieselOil"
      />
      <Gasoline
        ref="Gasoline"
        v-model="isShowGasolineDialog"
        :report-data.sync="reportData"
        @closeGasoline="closeGasoline"
      />
    </el-dialog>
    <ChoiceUserMessage
      ref="ChoiceUserMessage"
      :dialog-form-visible="dialogFormVisibleUser"
      @closeChioseUser="closeChioseUser"
    />

    <BasePreviewFile
      v-if="previewFileShow"
      :preview-file-show.sync="previewFileShow"
      :preview-file.sync="filepreview"
      :preview-file-list.sync="filepreviewList"
    />

    <!-- <PreviewFileDialog
      v-if="previewFileShow"
      :preview-file-show.sync="previewFileShow"
      :preview-file="filepreview"
    /> -->
  </div>
</template>
<script>
// import PreviewFileDialog from "@/ModuleEntrust/views/EntrustManage/EntrustOrder/PreviewFileDialog.vue";
// import ModuleEntrust from "panna-module-entrust";
import { mapGetters } from "vuex";
 import ChoiceUserMessage from "@/ModuleSample/views/SampleManage/SampleRegistration/ChoiceUserMessage.vue";
import { shortTime } from "../../../utils/moment.js";
import { getDictList, getConfigByKey } from "../../../api/System/SystemDict.js";
import {
  create,
  Get,
  GenerateReportCDC,
  getListNoPage,
  GetOilsReportNumber,
} from "../../../api/Report/ReportManage.js";
import _ from "lodash";
import AmbientGas from "../../../components/ReportTemplate/AmbientGas.vue";
import DieselOil from "../../../components/ReportTemplate/DieselOil.vue";
import Gasoline from "../../../components/ReportTemplate/Gasoline.vue";
import { getList } from "../../../api/Report/ReportSampleRegistration.js";
import { GetListBySampleCategoryId } from "../../../api/Report/SysBusinessReportTemplate";
import { GetStaticFileInfo } from "@/api/Base";

export default {
  name: "GenerateReportDialog",
  components: {
    ChoiceUserMessage,
    AmbientGas,
    DieselOil,
    Gasoline,
    // PreviewFileDialog: ModuleEntrust ? ModuleEntrust.PreviewFileDialog : null,
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Array,
      default: () => [],
    },
    reportManageId: {
      type: String,
      default: "",
    },
    fromSource: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      disabled: true,
      timer: "",
      // 系统类型
      systemType: "",
      reportTemplateState: [],
      reportTemplateProp: "",
      pagination: {
        pageIndex: 1,
        pageSize: 10,
      },
      previewFileShow: false,
      title: "生成报告",
      submitLoad: true,
      dialogFormVisibleUser: false,
      isShowAmbientGasDialog: false,
      isShowDieselOilDialog: false,
      isShowGasolineDialog: false,
      downloadState: true,
      submitReadOnly: false,
      innerDialogFormVisible: false,
      filepreviewList: [],
      filepreview: {
        fileName: "",
        url: "",
        storageFileName: "",
      },
      formData: {
        entrustOrderId: "",
        reportNum: "",
        reportNumberTypeEnum: "",
        reportConclusionEnum: "",
        permissionUserName: this.$store.getters.name,
        compilePerson: this.$store.getters.currentUserId,
        compileDate: shortTime(new Date()),
        generatePerson: this.$store.getters.currentUserId,
        reportTypeCode: 0,
        reportStatusCode: 10,
        remark: "",
        reportTemplateId: "",
        sampleRegistrationIdList: [],
        url: "",
      },

      formRules: {
        reportTypeCode: [
          { required: true, message: "请选择报告形式", trigger: "blur" },
        ],
        reportTemplateId: [
          { required: true, message: "请选择报告模板", trigger: "blur" },
        ],
        reportConclusionEnum: [
          { required: true, message: "请选择是否评价", trigger: "blur" },
        ],
        reportNum: [
          { required: true, message: "请填写报告编号", trigger: "blur" },
        ],
      },
      reportNumTypeData: [],
      reportConclusionTypeData: [],
      reportTypeList: [],
      reportTemplateList: [],
      reportData: [],
      reportId: [],
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
  },
  watch: {},
  created() {
    // 查询字典表判断系统类型
    getConfigByKey("SystemType").then((res) => {
      this.systemType = res.data[0].value;
      if (this.systemType === "thirdparty") {
        // 查询ELN域名
        // 查询字典表判断系统类型;
        getConfigByKey("ELN").then((res) => {
          this.formData.url = res.data[0].value;
        });
      }

      this.getData();
    });
  },
  methods: {
    preview() {
      this.previewFileShow = true;
    },
    getData() {
      // 判断是否是审批的内容的弹框
      if (this.fromSource === "ReportVerify") {
        this.innerGetList();
      } else {
        GetListBySampleCategoryId({
          id: this.rowData[0].sampleCategoryParentId,
        }).then((res) => {
          if (
            res.data !== null &&
            res.data.length !== 0 &&
            res.data !== undefined
          ) {
            this.formData.reportNumberTypeEnum = res.data[0].reportNumType;
            // 报告形式
            debugger
            this.formData.reportTypeCode = Number(res.data[0].reportTypeEnum);
            var reportTemplateId = res.data[0].id;
          }
          this.gainReportNum();

          // this.radioChange(this.formData.reportTypeCode);
          getDictList({ dictCode: "ReportType" }).then((res) => {
            this.reportTypeList = res.data;
          });
          // 查询报告模板
          getListNoPage({}).then((res) => {
            this.reportTemplateList = res.data;

            for (let i = 0; i < this.reportTemplateList.length; i++) {
              this.reportTemplateState.push(true);
            }
            this.radioChange(this.formData.reportTypeCode);
            this.formData.reportTemplateId = reportTemplateId;
          });
        });

        this.formData.entrustOrderId = this.rowData[0].entrustOrderId;
        this.formData.reportConclusionEnum = this.rowData[0].evaluateState;
        // 报告形式
        // getDictList({ dictCode: "ReportType" }).then((res) => {
        //   this.reportTypeList = res.data;
        // this.formData.reportTypeCode = this.rowData[0].reportType;
        // // 查询报告模板
        // getListNoPage({}).then((res) => {
        //   this.reportTemplateList = res.data;
        //   for (let i = 0; i < this.reportTemplateList.length; i++) {
        //     this.reportTemplateState.push(true);
        //   }
        //   this.radioChange(this.formData.reportTypeCode);
        // });
        // });
        // 是否评价
        getDictList({ dictCode: "ReportConclusionType" }).then((res) => {
          this.reportConclusionTypeData = res.data;
        });
        this.innerDialogFormVisible = this.dialogFormVisible;
      }
    },
    radioChange(data) {
      for (let i = 0; i < this.reportTemplateList.length; i++) {
        var arr = this.reportTemplateList[i].scope.split(",");
        for (let o = 0; o < arr.length; o++) {
          if (Number(arr[o]) === Number(data)) {
            this.reportTemplateState[i] = false;
            break;
          } else {
            this.reportTemplateState[i] = true;
          }
        }
      }
      this.timer = new Date().getTime();
      // if (this.systemType === "thirdparty") {
      //   this.reportTemplateProp = "reportTemplateId";
      //   for (let i = 0; i < this.reportTemplateList.length; i++) {
      //     if (this.reportTemplateList[i].scope.indexOf(data) >= 0) {
      //       this.reportTemplateState[i] = false;
      //     } else {
      //       this.reportTemplateState[i] = true;
      //     }
      //   }
      // } else if (this.systemType === "cdc") {
      //   for (let i = 0; i < this.reportTemplateState.length; i++) {
      //     this.reportTemplateState[i] = false;
      //   }
      // }
      this.formData.reportTemplateId = "";
    },
    innerGetList() {
      // 获取任务ID
      this.loading = true;
      Get({ id: this.reportManageId })
        .then((res) => {
          var obj = {};
          obj.entrustOrderId = res.data.entrustOrderId;
          getList({ ...obj, ...this.pagination })
            .then((res) => {
              this.rowData = [];
              this.rowData.push(res.data.dataList[0]);
              this.gainReportNum();
              this.formData.entrustOrderId = this.rowData[0].entrustOrderId;
              // 报告形式
              getDictList({ dictCode: "ReportType" }).then((res) => {
                this.reportTypeList = res.data;
                this.formData.reportTypeCode = this.rowData[0].reportType;
              });
              // 是否评价
              getDictList({ dictCode: "ReportConclusionType" }).then((res) => {
                this.reportConclusionTypeData = res.data;
              });
              // 查询报告模板
              getListNoPage({}).then((res) => {
                this.reportTemplateList = res.data;
              });
              this.innerDialogFormVisible = true;
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch((res) => { });
    },
    // 报告编号类型改变
    reportNumberTypeChange(val) {
      if (val === -1) {
        this.formData.reportNum = '';
        this.disabled = false;
      } else if (val === 2) {
        this.formData.reportNum = this.rowData[0].sampleNum;
        this.disabled = true;
      } else if (val === 1) {
        this.formData.reportNum = this.rowData[0].orderNum;
        this.disabled = true;
      } else if (val === 3) {
        // 油品编号
        GetOilsReportNumber(false).then((res) => {
          this.formData.reportNum = res.data;
          this.disabled = true;
        });
      }
    },
    // 获取报告编号
    gainReportNum() {
      // 委托单编号为空状态
      var entrueNumIsNull = 0;
      // 多样品状态
      var moreSampleState = 0;
      // 多委托单
      var moreEntrueState = 0;
      // 存样品编号
      var sampleNum = this.rowData[0].sampleNum;
      // 存委托单编号
      var entrueNum = this.rowData[0].orderNum;
      for (let i = 0; i < this.rowData.length; i++) {
        this.formData.sampleRegistrationIdList.push(this.rowData[i].id);
        // 判断是否有不同的样品编号
        if (sampleNum !== this.rowData[i].sampleNum) {
          moreSampleState = 1;
        }
        // 判断编号是否为空
        if (
          this.rowData[i].orderNum !== null &&
          this.rowData[i].orderNum !== ""
        ) {
          entrueNumIsNull = 1;
        }
        // 如果entrueNum存的本就是空,就在循环中找到有值的赋值
        if (entrueNum === null || entrueNum === "") {
          if (
            this.rowData[i].orderNum !== null &&
            this.rowData[i].orderNum !== ""
          ) {
            entrueNum = this.rowData[i].orderNum;
          }
        }
        // 判断是否有不同委托单号
        if (entrueNum !== this.rowData[i].orderNum) {
          moreEntrueState = 1;
        }
      }
      // 0显示全部选项，1显示委托单号，2选择样品编号,3自定义
      var selectDataSate = 0;
      // 如果多样品多委托单状态为0,并且委托单号不能为空
      if (
        moreSampleState === 0 &&
        moreEntrueState === 0 &&
        entrueNumIsNull !== 0
      ) {
        selectDataSate = 0;
      }
      // 只能自定义编号，条件多个不同样品并且多个不同委托单或者多个不同样品，委托单编号都为空
      if (
        (moreSampleState === 1 && moreEntrueState === 1) ||
        (moreSampleState === 1 && entrueNumIsNull === 0)
      ) {
        selectDataSate = 3;
      } else if (
        // 只有样品编号和自定义编号，条件委托单为空并且样品编号相同，或者委托单编号不相同，样品编号相同
        (entrueNumIsNull === 0 && moreSampleState === 0) ||
        (moreEntrueState === 1 && moreSampleState === 0)
      ) {
        selectDataSate = 2;
      } else if (
        // 只有委托单号和自定义编号,条件委托单号不能为空，样品编号不相同，委托单号相同
        entrueNumIsNull !== 0 &&
        moreSampleState === 1 &&
        moreEntrueState === 0
      ) {
        selectDataSate = 1;
      }

      // 编号类型
      getDictList({ dictCode: "ReportNumType" }).then((res) => {
        var data = [];
        if (selectDataSate !== 0) {
          for (let i = 0; i < res.data.length; i++) {
            if (Number(res.data[i].value) === selectDataSate) {
              data.push(res.data[i]);
            }
          }
        } else {
          data = res.data;
        }
        this.reportNumTypeData = data;
        var state = false;
        var reportNumType = 0;
        for (let i = 0; i < this.reportNumTypeData.length; i++) {
          if (
            Number(this.reportNumTypeData[i].value) ===
            Number(this.formData.reportNumberTypeEnum)
          ) {
            state = true;
          } else {
            reportNumType = Number(this.reportNumTypeData[i].value);
          }
        }
        if (!state) {
          this.formData.reportNumberTypeEnum = reportNumType;
        }
        // 复现选中的报告编号类型
        this.reportNumberTypeChange(this.formData.reportNumberTypeEnum);
      });
    },
    // 下载
    download() {
      if (this.reportId.length <= 0) {
        this.$message({
          message: "请先保存再下载",
          type: "warning",
        });
        return;
      }
      const id = this.reportId[0];
      // 获取报告
      Get({ id: id }).then((res) => {
        if (res.code === 200) {
          console.log(res)
          var fileUrl = `${res.data.reportUrl}`;
          GetStaticFileInfo(fileUrl, res.data.reportNum + ".docx");

          // var fileUrl = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${res.data.reportUrl}`;

          // this.getBlob(fileUrl).then((blob) => {
          //   this.saveAs(blob, res.data.reportNum + ".docx");
          // });
        }
      });
    },
    // 下载文件js模拟点击a标签进行下载
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },
    // 通过文件下载url拿到对应的blob对象
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    // 点击保存
    onSubmit: _.throttle(function(formName) {
      if (this.submitLoad) {
        this.submitLoad = false;

        var data = this.reportTemplateList.filter(
          (item) => item.id === this.formData.reportTemplateId
        );
        if (data !== null && data.length !== 0) {
          if (Number(data[0].tpye) !== 2) {
            if (this.formData.sampleRegistrationIdList.length > 1) {
              this.$message.error("选择的报告模板仅支持一个样品");
              this.submitLoad = true;
              return false;
            }
          }
        }
        debugger
        if (this.formData.reportTypeCode === 0) {
          this.$message.error("请选择报告形式");
          this.submitLoad = true;
          return false;
        }
        if (
          this.formData.reportTemplateId === "" ||
          this.formData.reportTemplateId === null
        ) {
          this.$message.error("请选择报告模板");
          this.submitLoad = true;
          return false;
        }
        if (
          this.formData.reportConclusionEnum === "" ||
          this.formData.reportConclusionEnum === null ||
          this.formData.reportConclusionEnum === 0
        ) {
          this.$message.error("请选择是否评价");
          this.submitLoad = true;
          return false;
        }

        this.$refs.formData.validate((valid) => {
          if (valid) {
            if (this.systemType === "thirdparty") {
              create(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message({
                      message: "操作成功",
                      type: "success",
                    });
                    // this.submitLoad = true;
                    this.submitReadOnly = true;
                    this.downloadState = false;
                    res.data.forEach((element) => {
                      this.filepreview.fileName = element.reportFileName;
                      this.filepreview.url = element.reportUrl;
                      this.filepreview.storageFileName = element.reportFileName;
                      this.filepreviewList.push(
                        JSON.parse(JSON.stringify(this.filepreview))
                      );
                    });
                    this.reportId.push(res.data[0].id);
                    this.previewFileShow = true;
                  }
                })
                .catch(() => {
                  this.submitLoad = true;
                });
            } else if (this.systemType === "cdc") {
              GenerateReportCDC(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message({
                      message: "操作成功",
                      type: "success",
                    });
                    // this.submitLoad = true;
                    this.submitReadOnly = true;
                    this.downloadState = false;

                    this.filepreview.fileName = res.data.reportFileName;
                    this.filepreview.url = res.data.reportUrl;
                    this.filepreview.storageFileName = res.data.reportFileName;
                    this.reportId.push(res.data.id);
                    this.previewFileShow = true;
                  }
                })
                .catch(() => {
                  this.submitLoad = true;
                });
            }
          } else {
            this.submitLoad = true;
          }
        });
      }
    }, 2000),
    // 关闭汽油组分弹窗
    closeGasoline() {
      this.isShowGasolineDialog = false;
      this.reportData = [];
    },
    // 关闭柴油组分弹窗
    closeDieselOil() {
      this.isShowDieselOilDialog = false;
      this.reportData = [];
    },
    // 选择的人员信息
    closeReport() {
      this.isShowGasolineDialog = false;
      this.reportData = [];
    },
    // 预览模板
    previewReport(val) {
      if (val === "1") {
        this.isShowGasolineDialog = true;
      } else if (val === "2") {
        this.isShowDieselOilDialog = true;
      }
    },
    // 选择的人员信息
    closeChioseUser(data) {
      this.dialogFormVisibleUser = false;
      this.formData.permissionUserName = data.name;
      this.formData.compilePerson = data.id;
    },
    // 选择人员
    chioseUser() {
      this.dialogFormVisibleUser = true;
    },
    // 关闭弹框
    handleClose() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$emit("update:rowData", []);
      this.$parent.getList();
      this.reportId = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.chioseUser {
  width: 30px;
  color: white;
  font-size: 20px;
  height: 32px;
  text-align: center;
  border-radius: 5px;
  border: 1px silver;
  background-color: #4787ff;
  position: absolute;
  top: 0px;
  right: 0px;
}
</style>
